package com.mach.platform.utils;

import com.github.pagehelper.util.StringUtil;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.util.List;

public final  class FileUtil {
    private FileUtil(){}

    /**
     * 获取后缀
     * @param fileName 文件名
     * @return 后缀名
     */
    public static String getFileSuffix(String fileName){
        if(StringUtil.isEmpty(fileName) || fileName.lastIndexOf(".")<0 ){
            return "error";
        }
        return fileName.substring(fileName.lastIndexOf(".")+1);
    }

    /**
     * 保存文件到目录
     * @param request 文件列表
     * @param filePath 文件目录
     * @return
     */
    public static String saveFile(HttpServletRequest request, String filePath) {
        List<MultipartFile> files = ((MultipartHttpServletRequest) request).getFiles("file");
        String result = "上传成功";
        MultipartFile file = null;
        BufferedOutputStream stream = null;
        for (int i = 0; i < files.size(); ++i) {
            file = files.get(i);

            if (!file.isEmpty()) {
                try {
                    byte[] bytes = file.getBytes();
                    stream = new BufferedOutputStream(new FileOutputStream(
                            new File(filePath + file.getOriginalFilename())));//设置文件路径及名字
                    stream.write(bytes);// 写入
                    stream.close();
                } catch (Exception e) {
                    stream = null;
                    result = "第 " + i + " 个文件上传失败 ==> "
                            + e.getMessage();
                    return result;
                }
            } else {
                result =  "第 " + i
                        + " 个文件上传失败因为文件为空";
                return result;
            }
        }
        return result;
    }
}